use serde::Serialize; // For serializing custom structs to send to frontend
use std::fs;
use std::path::Path;

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[derive(Serialize, Debug)] // Added Debug for easier error logging if needed
struct FileEntry {
    name: String,
    is_directory: bool,
    // path: String, // Might be useful to return the full path too
}

#[tauri::command]
fn list_directory_contents(path: String) -> Result<Vec<FileEntry>, String> {
    let mut entries = Vec::new();
    let readdir = match fs::read_dir(Path::new(&path)) {
        Ok(readdir) => readdir,
        Err(e) => return Err(format!("Failed to read directory '{}': {}", path, e.to_string())),
    };

    for entry_result in readdir {
        match entry_result {
            Ok(entry) => {
                let file_name_os_str = entry.file_name();
                let file_name = match file_name_os_str.into_string() {
                    Ok(name) => name,
                    Err(_) => {
                        // Log or handle invalid UTF-8 names, skip for now
                        eprintln!("Skipping entry with invalid UTF-8 name in path: {}", path);
                        continue;
                    }
                };
                
                let metadata = match entry.metadata() {
                    Ok(md) => md,
                    Err(e) => {
                        eprintln!("Failed to get metadata for {:?}: {}", entry.path(), e.to_string());
                        // Skip problematic entries or return an error for the whole operation
                        continue; 
                    }
                };
                entries.push(FileEntry {
                    name: file_name,
                    is_directory: metadata.is_dir(),
                    // path: entry.path().to_string_lossy().into_owned(),
                });
            }
            Err(e) => {
                // Log error or handle it
                eprintln!("Error reading directory entry in '{}': {}", path, e.to_string());
                // Depending on desired behavior, could return an error or skip
            }
        }
    }
    Ok(entries)
}

#[tauri::command]
fn create_folder(path: String) -> Result<(), String> {
    match fs::create_dir_all(&path) {
        Ok(_) => Ok(()),
        Err(e) => Err(format!("Failed to create folder '{}': {}", path, e.to_string())),
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![greet, list_directory_contents, create_folder])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
